<template>
  <a-modal
    title="活动管理"
    :width="800"
    :visible="visible"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="活动类型">
          <a-radio-group buttonStyle="solid" :disabled="isDisabled"
                         v-decorator="[ 'type', {rules: [{ required: true, message: '请选择' }], initialValue: 1}]">
            <a-radio-button :value="1">礼品商城</a-radio-button>
            <a-radio-button :value="2">趣味游戏</a-radio-button>
            <a-radio-button :value="3">限时抢购</a-radio-button>
            <a-radio-button :value="4">限时秒杀</a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="活动名称">
          <a-input placeholder="活动名称" :disabled="isDisabled"
                   v-decorator="[ 'name', {rules: [{required: true, message: '请选择。。。' }] }]"/>
        </a-form-item>
        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="有效时间">
          <a-range-picker style="width: 100%"
                          :format="dateFormat"
                          :showTime="{ format: 'HH:mm' }"
                          :placeholder="['开始时间', '结束时间']"
                          v-decorator="[ 'validTime', {rules: []}]"
          />
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="每人每天抽奖次数">
          <a-input placeholder="每人每天抽奖次数" v-decorator="[ 'oneDayCount', {rules: [{ required: true, message: '请输入。。。' }] }]"></a-input>
        </a-form-item>
        <a-form-item
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          label="商品配置"
        >
          <div v-for="(item,i) in items">
            <a-select style="width: 35%" placeholder="请选择" v-model="item.couponId">
              <a-select-option v-for="pw in couponList" :key="pw.id">{{pw.stockName}}</a-select-option>
            </a-select>
            <span style="margin-left: 10px">权重：</span>
            <a-input style="width: 38%" addonAfter="数字" v-model="item.rate"/>&nbsp;
            <a-button style="width: 15%" type="danger" @click="onDel(i)">删除</a-button>
          </div>
          <a-button @click="onAdd" type="primary" style="margin-top: 6px">添加</a-button>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="图片">
          <a-upload
            listType="picture-card"
            class="avatar-uploader"
            :showUploadList="false"
            :action="baseUrl + '/sys/upload/uploadFile'"
            :beforeUpload="beforeUpload"
            @change="handleChange"
          >
            <img v-if="imageUrl" :src="imageUrl" alt="avatar" width="300px"/>
            <div v-else>
              <a-icon :type="confirmLoading ? 'loading' : 'plus'"/>
              <div class="ant-upload-text">选择图片</div>
            </div>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
  import moment from 'moment'
  import pick from 'lodash.pick'
  import { selectAllByParentCode } from '@/api/shop/coupon'
  import { updateActivity } from '@/api/shop/activity'

  export default {
    data () {
      return {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 15 }
        },
        dateFormat: 'YYYY-MM-DD HH:mm',
        baseUrl: process.env.VUE_APP_API_BASE_URL,
        id: null,
        parentCode: null,
        visible: false,
        confirmLoading: false,
        isDisabled: false,
        imageUrl: null,
        fileName: null,
        couponList: [],
        items: [],
        form: this.$form.createForm(this)
      }
    },
    mounted () {

    },
    methods: {
      add (parentCode) {
        this.visible = true
        this.parentCode = parentCode
      },
      edit (record) {
        this.items = record.detailList
        selectAllByParentCode({parentCode: record.parentCode, activityType: record.type}).then(res => {
          if (res.code === 200) {
            this.couponList = res.result
            this.visible = true
            this.isDisabled = true
            this.id = record.id
            this.imageUrl = record.fileUrl
            const { form: { setFieldsValue } } = this
            let validTime = []
            if (record.beginTime) {
              validTime.push(moment(record.beginTime))
              validTime.push(moment(record.endTime))
              record.validTime = validTime
            }
            this.$nextTick(() => {
              const formData = pick(record, ['type','customerName', 'name', 'validTime', 'idList', 'oneDayCount'])
              setFieldsValue(formData)
            })
          }
        })

      },
      handleSubmit () {
        const { form: { validateFields } } = this
        this.confirmLoading = true
        validateFields((errors, values) => {
          if (!errors) {
            values.id = this.id
            values.filename = this.filename
            values.parentCode = this.parentCode
            values.beginTime = values['validTime'][0].format('YYYY-MM-DD HH:mm') + ":00"
            values.endTime = values['validTime'][1].format('YYYY-MM-DD HH:mm') + ":00"
            values.detailList = this.items
            updateActivity(values).then((res) => {
              this.confirmLoading = false
              if (res.code === 200) {
                this.handleCancel()
                this.$emit('ok')
              }
            })
          } else {
            this.confirmLoading = false
          }
        })
      },
      filterOption (input, option) {
        return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      },
      handleCancel () {
        this.visible = false
        this.form.resetFields()
        this.id = null
        this.imageUrl = null
        this.filename = null
      },
      handleChange (info) {
        if (info.file.status === 'uploading') {
          this.confirmLoading = true
          return
        }
        if (info.file.status === 'done') {
          // Get this url from response in real world.
          this.imageUrl = info.file.response.fileUrl
          this.filename = info.file.response.filename
          this.confirmLoading = false
        }
      },
      beforeUpload (file) {
        // const isJPG = file.type === 'image/jpeg';
        // if (!isJPG) {
        //   this.$message.error('You can only upload JPG file!');
        // }
        // const isLt2M = file.size / 1024 / 1024 < 2;
        // if (!isLt2M) {
        //   this.$message.error('Image must smaller than 2MB!');
        // }
        return true
      },
      onAdd () {
        let cope = {}
        this.items.push(cope)
        // console.log(this.items);
      },
      onDel: function (index) {
        this.items.splice(index, 1)
      }
    }
  }
</script>
